import editForm from "../form.vue";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw, h, computed } from "vue";
import {
  createGlobalAgentConfContext,
  getAgentSettingList,
  saveAgentSetting
} from "@/api/agent";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { agentSettingType } from "@/utils/commonType";
import { ElMessageBox } from "element-plus";

export function useAgentOptions(tableRef: Ref) {
  const form = reactive({
    optionItem: "",
    section: "global"
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 80]
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 60
    },
    {
      label: "配置项",
      prop: "optionItem",
      minWidth: 100
    },
    {
      label: "配置项说明",
      prop: "optionDesc",
      minWidth: 100
    },
    {
      label: "配置值",
      prop: "optionValue",
      minWidth: 140
    },
    {
      label: "配置值说明",
      prop: "settingDesc"
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    // selectedNum.value = val.length;
    // // 重置表格高度
    // tableRef.value.setAdaptive();
  }

  async function onSearch() {
    loading.value = true;
    const section = form.section;
    const params = {
      ...pagination,
      optionItem: form.optionItem
    };
    getAgentSettingList(section, params)
      .then(result => {
        dataList.value = result.data.list;
        pagination.total = result.data.total;
        pagination.pageSize = result.data.pageSize;
        pagination.currentPage = result.data.currentPage;
        pagination.pageCount = result.data.totalPage;
      })
      .catch(err => {
        message(`获取配置清单失败：${err.message}`, {
          type: "error"
        });
      });

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const formRef = ref();

  function openDialog(title = "新增", row?: agentSettingType) {
    addDialog({
      title: `${title}代理配置`,
      props: {
        formInline: {
          belongId: row?.belongId ?? "",
          belongType: "global",
          optionValue: row?.optionValue ?? "",
          settingDesc: row?.settingDesc ?? "",
          pid: row?.pid ?? "",
          section: row?.section ?? "",
          optionItem: row?.optionItem ?? "",
          optionDesc: row?.optionDesc ?? "",
          editStatus: title == "新增" ? false : true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as agentSettingType;
        function chores() {
          message(`成功保存代理配置${curData.optionItem}`, {
            type: "success"
          });
          done(); // 关闭弹框
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            saveAgentSetting(curData)
              .then(result => {
                chores();
                onSearch();
              })
              .catch(err => {
                message(
                  `保存代理配置${curData.optionItem}异常：${err.message}`,
                  {
                    type: "success"
                  }
                );
              });
          }
        });
      }
    });
  }
  function createGlobalAgentConf() {
    ElMessageBox.confirm(`确认要重新生成全局代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        createGlobalAgentConfContext()
          .then(result => {
            message(`全局代理配置内容生成成功：${result.data}`, {
              type: "success"
            });
          })
          .catch(err => {
            message(`全局代理配置内容生成失败：${err.message}`, {
              type: "error"
            });
          });
      })
      .catch(() => {});
  }
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    resetForm,
    openDialog,
    createGlobalAgentConf,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
